<?php
namespace app\index\controller;

use app\index\model\User as UserModel;
use think\Controller;

class User extends Controller
{
    //渲染登入页面
    public function login()
    {
        return $this->fetch();
    }

    //渲染注册页面
    public function register()
    {
        return $this->fetch();
    }

    //登入事件逻辑
    public function loginEvent()
    {

        $username = $_POST['username']; //获取用户名
        $password = $_POST['password']; //获取密码

        //验证字段
        $validateData = [
            'name' => $username,
            'password' => $password,
        ];
        $result = $this->validate($validateData, "User");

        if (true !== $result) { //验证失败
            $this->error($result, 'index/user/login');
        } else {
            $user = model('User')->getUserByUserName($username);
            if ($user) {
                if ($user->password == $password) { //注册成功
                    session('username', $username);
                    session('id', $user->id);
                    $this->redirect("index/index/index");
                } else {
                    $this->error('密码不正确', 'index/user/login');
                }
            } else {
                $this->error('请输入正确的用户名', 'index/user/login');
            }
        }
    }

    //退出登入
    public function outLogin() {
        session('username', null);
        session('id', null);
        $Index = new \app\index\controller\Index;
        $this->redirect("index/Index/index");
    }

    //注册事件的发生
    public function registerEvent()
    {
        $file = request()->file('file');    //获取文件
        $info = NULL;   //文件存储
        if (!empty($file)) {
            $info = $file->rule('uniqid')->move(ROOT_PATH . 'upload' . DS . 'image');
        }
        
        $username = $_POST['username'];
        $password = $_POST['password'];
        $email = $_POST['email'];

        //验证数据
        $validateData = [
            'name' => $username,
            'password' => $password,
        ];
        $result = $this->validate($validateData, "User");
        if (true !== $result) {
            $this->error($result, 'index/user/register');
        }

        $data = [
            'username' => $username,
            'password' => $password,
            'email' => $email,
            'update_time' => time(),
            'create_time' => time(),
            'status' => 1,
            'img_url' => $info && $info->getFileName(),
        ];

        //插入一条记录
        $newUser = new UserModel($data);
        $result = $newUser->save();

        if ($result) {
            $this->success('ADD User sucessfully', 'index/user/login');

        } else {
            $this->error('ADD User failed!', 'index/user/register');
        }

    }
}
